package brau.persistence;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.Query;

import org.slf4j.Logger;

import br.gov.frameworkdemoiselle.stereotype.PersistenceController;
import br.gov.frameworkdemoiselle.template.JPACrud;
import brau.constant.SituacaoEnum;
import brau.domain.Endereco;

@PersistenceController
public class EnderecoDAO extends JPACrud<Endereco, Long> {
	
	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unused")
	@Inject private Logger logger;

	
	public List<Endereco> buscarEnderecoByfilter (String filter) {
		filter = filter.trim().toUpperCase();
		String hql = "select en " +
					 "from Endereco en ";
		if ( ! filter.isEmpty()) { 
			if (filter.contains("  ")) filter = filter.replaceAll("  ", " ");
			if (filter.contains(" ")) filter = filter.replaceAll(" ", "%");
			filter = "'%"+filter+"'%";
			hql+= "where upper(en.logradouro) like "+filter+" " +
					"or upper(en.bairro) like "+filter+" " +
					"or upper(en.localidade) like "+filter+" " +
					"or upper(en.uf) like "+filter+" " +
					"or upper(en.cep) like "+filter+" ";
		}
		hql +=	"order by en.cep";

		Query query = getEntityManager().createQuery(hql);
		@SuppressWarnings("unchecked")
		List<Endereco> listaEndereco = query.getResultList();
		return listaEndereco;
	}

	@SuppressWarnings("unchecked")
	public Endereco buscarEnderecoByPontoXY(Double pontoX, Double pontoY){
		String hql = "select e " +
					 "from Endereco e " +
					 "where e.pontoX = :pontoX " +
					 "and e.pontoY = :pontoY " +
					 "and e.situacao = :situacao";
		Query query = getEntityManager().createQuery(hql);
		query.setParameter("pontoX", pontoX);
		query.setParameter("pontoY", pontoY);
		query.setParameter("situacao", SituacaoEnum.Ativo.getCodigo());
		List<Endereco> lista = query.getResultList();
		if (lista.size() > 0) return lista.get(0);
		return null;
	}

}